<?php

namespace app\api\controller;

use app\admin\model\Category;
use app\admin\model\CategoryIncome;
use app\admin\model\CategoryQuan;
use app\admin\model\Faq;
use app\admin\model\MiniImage;
use app\admin\model\Order;
use app\admin\model\OrderProcHelp;
use app\admin\model\RechargeRecord;
use app\admin\model\RechargeRule;
use app\admin\model\UserCategoryRmb;
use app\common\controller\Api;
use app\common\model\Config;
use app\common\model\DouyinLogic;
use app\common\model\MeituanLogic;
use think\Db;
use think\Log;
use Zxing\QrReader;
use think\Config as sConfig;

/**
 * 接口
 */
class Dylogic extends Api
{
    //无需登录的方法,同时也就不需要鉴权了
    protected $noNeedLogin = [
        'pay_order_notifyx',
        'pay_recharge_notifyx',
        'get_mini_images',
        'get_config',
        'test',
        'run_timer',
        'getFaqList',
        'getOrderProcHelpList',
    ];
    //无需鉴权的方法,但需要登录
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
        // $this->auth->direct(141);
        //解锁锁定
        CategoryQuan::unlockExpireQuan();
    }


    // https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/index.php/api/dylogic/run_timer
    public function run_timer()
    {
        //解锁锁定
        CategoryQuan::unlockExpireQuan();
        exit("锁定超过30分钟的优惠券已解锁!");
    }



    //http://cfmt.test/api/dylogic/getShopList
    //http://cfmt.test/api/dylogic/getShopList?lng=116.404&lat=39.915
    //http://cfmt.test/api/dylogic/getShopList?lng=116.404&lat=39.915&query_word=169
    //http://cfmt.test/api/dylogic/getShopList?lng=116.404&lat=39.915&query_word=128
    //获取category门店列表
    public function getShopList()
    {
        $lng = input('lng', 0);
        $lat = input('lat', 0);
        $page = input('page', 1);
        $limit = input('limit', 10);
        $isDouyin = input('is_douyin', 0);
        $isMeituan = input('is_meituan', 0);
        $query_word = input('query_word', "");
        $user_id = $this->auth->id;

        //如果有经纬度参数,则按照经纬度参数进行排序
        if ($lng && $lat) {
            //按距离排序读取出 Category中的 全部数据,并且将距离存入dy_distance字段,按千米为单位
            //    `lng` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '经度',
            //   `lat` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '纬度',
            // $all_category = Category::field('*,ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lng*PI()/180)/2),2)))*1000) as dy_distance')->select();

            $query_obj = Category::field(
                '*,ROUND(6378.138*2*ASIN(SQRT(POW(SIN((' . $lat . '*PI()/180-lat*PI()/180)/2),2)+COS(' . $lat . '*PI()/180)*COS(lat*PI()/180)*POW(SIN((' . $lng . '*PI()/180-lng*PI()/180)/2),2)))*1) AS dy_distance'
            );
        } else {
            //读取全部门店,新增一个字段dy_distance,值为0
            $query_obj = Category::field('*,999 as dy_distance');
        }

        if ($isDouyin){
            $query_obj = $query_obj->where('douyin_shop_id','>',0);
        }
        if ($isMeituan){
            $query_obj = $query_obj->where('meituan_open_id','<>','');
        }

        if (!empty($query_word)) {
            $query_obj = $query_obj->where('name', 'like', '%' . $query_word . '%');
        }

        $all_category = $query_obj->page($page, $limit)->order('dy_distance', 'asc')->select();

        //遍历全部门店
        foreach ($all_category as &$category) {
            //读取自身在这些门店的余额
            $category->order_proc_help;
            $category->faq;
            $category->recharge_rule;

            //将门店中image字段图片地址补全
            $category['image'] = cdnurl($category['image'], true);

            //将门店images字段转换为数组
            $new_images = explode(',', $category['images']);
            //将$category['images']中的图片地址,替换为完整的图片地址
            foreach ($new_images as &$image) {
                $image = cdnurl($image, true);
            }
            $category['images'] = $new_images;
            //读取自身在这些门店的余额
            $category['my_category_amount'] = UserCategoryRmb::GetAmount($user_id, $category->id);
        }
        //返回门店列表
        return $this->success('门店列表', $all_category);
    }

    //根据门店id获取门店详情,包括自己在此门店的余额
    //http://cfmt.test/api/dylogic/getShopDetail?category_id=35
    public function getShopDetail()
    {
        $category_id = input('category_id', 0);
        $user_id = $this->auth->id;
        //读取指定门店的数据
        $category = Category::get($category_id);
        //读取自身在这些门店的余额
        $category->order_proc_help;
        $category->faq;
        $category->recharge_rule;
        //将门店中image字段图片地址补全
        $category['image'] = cdnurl($category['image'], true);
        //将门店images字段转换为数组
        $new_images = explode(',', $category['images']);
        //将$category['images']中的图片地址,替换为完整的图片地址
        foreach ($new_images as &$image) {
            $image = cdnurl($image, true);
        }
        $category['images'] = $new_images;
        //读取自身在这些门店的余额
        $category['my_category_amount'] = UserCategoryRmb::GetAmount($user_id, $category->id);
        //返回门店详情
        return $this->success('门店详情', $category);
    }



    //http://cfmt.test/api/dylogic/getShopCanRechargeAmountList?category_id=35
    //获取指定门店的可充值金额列表
    public function getShopCanRechargeAmountList()
    {
        $category_id = input('category_id', 0);
        //读取指定门店的充值规则,且读取门店ID=0的数据
        $recharge_amount_list = RechargeRule::where('category_id', $category_id)->whereOr('category_id', 0)->select();
        //返回可充值金额列表
        return $this->success('门店可充值金额列表', $recharge_amount_list);
    }


    //http://cfmt.test/api/dylogic/uploadQrcodeScan
    //上传二维码图片,并识别该二维码的内容,返回内容给调用者
    public function uploadQrcodeScan()
    {
        //获取上传的文件
        $file = $this->request->file('file');
        if (!$file) {
            return $this->error('请上传文件');
        }
        //上传到本地服务器
        $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'upload_qrcode');
        //获取上传后的文件名
        $filename = $info->getSaveName();
        //拼接文件路径
        $filepath = '/uploads/upload_qrcode/' . $filename;

        //二维码的绝对路径
        $qrcode_path = ROOT_PATH . 'public' . DS . $filepath;

        $qrcode_reader = new QrReader($qrcode_path);
        $qrcode_text = $qrcode_reader->text(); //return decoded text from QR Code

        $data = [
            'filepath' => $filepath,
            'qrcode_text' => $qrcode_text,
        ];
        return $this->success('识别二维码完成', $data);
    }



    //http://cfmt.test/api/dylogic/getFaqList?category_id=35
    //读取Faq列表
    public function getFaqList()
    {
        $category_id = input('category_id', 0);
        //读取category_id和category_id=0的faq列表,并以category_id>0的数据优先展示
        $data_list = Faq::where('category_id', $category_id)->whereOr('category_id', 0)->order(
            'category_id desc'
        )->select();
        return $this->success('常见问题列表', $data_list);
    }


    //http://cfmt.test/api/dylogic/getOrderProcHelpList?category_id=35
    //读取下单流程 OrderProcHelp列表
    public function getOrderProcHelpList()
    {
        $category_id = input('category_id', 0);
        //读取category_id和category_id=0的faq列表,并以category_id>0的数据优先展示,weight越大越靠前
        $data_list = OrderProcHelp::where('category_id', $category_id)->whereOr('category_id', 0)->order(
            'category_id desc,weight desc'
        )->select();
        return $this->success('下单流程步骤', $data_list);
    }



    //http://cfmt.test/api/dylogic/getMyAllCategoryAmount
    //读取本用户所有门店的余额合计
    public function getMyAllCategoryAmount()
    {
        $user_id = $this->auth->id;
        //读取本用户所有门店的余额合计
        $my_all_category_amount = UserCategoryRmb::GetMyAllCategoryAmount($user_id);
        return $this->success('本用户所有门店的余额合计', $my_all_category_amount);
    }


    //http://cfmt.test/api/dylogic/getMyUnusedCouponList
    //获取我的优惠券列表 未使用
    public function getMyUnusedCouponList()
    {
        $user_id = $this->auth->id;
        $page = input('page', 1);
        $limit = input('limit', 10);
        //读取优惠券
        $my_coupon_list = CategoryQuan::where('user_id', $user_id)
            ->where('is_used', 0)
            ->where('quan_balance', '>', 0)
            ->where(
                'expire_time',
                '>',
                date('Y-m-d H:i:s')
            )->page($page, $limit)->select();
        //获取总数量
        $total = CategoryQuan::where('user_id', $user_id)
            ->where('is_used', 0)
            ->where('quan_balance', '>', 0)
            ->where(
                'expire_time',
                '>',
                date('Y-m-d H:i:s')
            )->count();
        $data = [
            'total' => $total,
            'list' => $my_coupon_list,
        ];
        return $this->success('我的未使用优惠券列表', $data);
    }

    //http://cfmt.test/api/dylogic/getMyUsedCouponList
    //获取我的优惠券列表 已使用
    public function getMyUsedCouponList()
    {
        $user_id = $this->auth->id;
        $page = input('page', 1);
        $limit = input('limit', 10);
        //读取优惠券,
        $my_coupon_list = CategoryQuan::where('user_id', $user_id)
            //闭包or查询
            ->where(function ($query) {
                //is_used=1 或者 expire_time(datetime)<当前时间
                $query->where('is_used', 1)
                    ->whereOr('quan_balance', '<=', 0)
                    ->whereOr('expire_time', '<', date('Y-m-d H:i:s'));
            })
            ->page($page, $limit)->select();
        //获取总数量
        $total = CategoryQuan::where('user_id', $user_id)
            ->where(function ($query) {
                //is_used=1 或者 expire_time(datetime)<当前时间
                $query->where('is_used', 1)
                    ->whereOr('quan_balance', '<=', 0)
                    ->whereOr('expire_time', '<', date('Y-m-d H:i:s'));
            })
            ->count();
        //遍历my_coupon_list, 根据过期原因,设置过期原因quan_status_text
        foreach ($my_coupon_list as $key => &$value) {
            if ($value->is_used == 1 || $value->quan_balance <= 0) {
                $value->quan_status_text = '已使用';
                continue;
            }
            if ($value->expire_time < date('Y-m-d H:i:s')) {
                $value->quan_status_text = '已过期';
                continue;
            }
            $value->quan_status_text = '已作废';
        }
        $data = [
            'total' => $total,
            'list' => $my_coupon_list,
        ];
        return $this->success('我的已使用优惠券列表', $data);
    }


    //http://cfmt.test/api/dylogic/getMyShopPayInfo?order_id=768
    //通过订单ID获取自身账户可用的门店余额和优惠券
    public function getMyShopPayInfo()
    {
        $order_id = input('order_id', 0);
        $order_info = Order::where('id', $order_id)->find();
        if (!$order_info) {
            return $this->error('订单不存在');
        }
        $fangjian_info = $order_info->fangjian;
        if (!$fangjian_info) {
            return $this->error('订单的房间已经不存在了!');
        }
        $category_info = $fangjian_info->category;
        if (!$category_info) {
            return $this->error('订单的房间对应的门店已经不存在了!');
        }
        // dump($category_info);

        $user_id = $this->auth->id;
        $my_category_rmb = UserCategoryRmb::GetAmount($user_id, $category_info->id);
        $my_category_quan_list = CategoryQuan::GetQuanList($user_id, $category_info->id);
        $data = [
            'user_id' => $user_id,
            'category_id' => $category_info->id,
            'my_category_rmb' => $my_category_rmb,
            'my_category_quan_list' => $my_category_quan_list,
        ];
        $this->success('获取订单可支付信息成功', $data);
    }


    //美团输入优惠券预兑换
    // 正常 http://cfmt.test/api/dylogic/meituanCouponExchangePreview?coupon_code=2306434509&category_id=38
    // 异常 http://cfmt.test/api/dylogic/meituanCouponExchangePreview?coupon_code=2306434509&category_id=33
    // 正常 http://cfmt.test/api/dylogic/meituanCouponExchangePreview?coupon_code=1151945478&category_id=38
    // 异常 http://cfmt.test/api/dylogic/meituanCouponExchangePreview?coupon_code=1151945478&category_id=33
    // {
    // "code": 1,
    // "msg": "美团团购券信息",
    // "time": "1679909566",
    // "data": {
    // "count": 1,  //团购券可用张数
    // "receipt_code": "2306434509",
    // "deal_id": 943017524,
    // "dealgroup_id": 776306224, //团购ID
    // "deal_title": "60分钟足部足疗", //团购商品名称
    // "deal_price": 1, //实际售卖价
    // "deal_marketprice": 120, //市场价
    // "mobile": "180****3089",
    // "product_type": null,
    // "product_item_id": null,
    // "biz_type": 0,  //业务类型 0:普通团购 205:次卡
    // "payment_detail": [
    // {
    // "payment_detail_id": "49089458374163761471M9P50101",
    // "amount": 1,
    // "amount_type": 10
    // }
    // ],
    // "receipt_info_map": null,
    //         "receiptEndDate": 1687708799000
    //         }
    //         }
    public function meituanCouponExchangePreview()
    {
        $user_id = $this->auth->id;
        $category_id = input('category_id', 0);
        $coupon_code = input('coupon_code', '');

        //读取门店信息
        $category_info = Category::get($category_id);
        if (!$category_info) {
            return $this->error('门店不存在');
        }
        //读取门店关联的美团授权信息
        $meituan_auth_info = $category_info->meituan_auth;
        if (!$meituan_auth_info) {
            return $this->error('门店未授权美团');
        }

        $app_key = $meituan_auth_info['app_key'];
        $app_secret = $meituan_auth_info['app_secret'];
        $session = $meituan_auth_info['session'];
        $receipt_code = $coupon_code; //美团团购券码
        $open_shop_uuid = $category_info['meituan_open_id']; //美团门店ID

        //读取美团团购券
        $meituan_coupon_info = MeituanLogic::ReceiptPrepare(
            $app_key,
            $app_secret,
            $session,
            $receipt_code,
            $open_shop_uuid
        );
        if ($meituan_coupon_info['code'] !== 200) {
            return $this->error($meituan_coupon_info['msg']);
        }

        $meituan_coupon_data = $meituan_coupon_info['data'];
        //只支持biz_type=0的普通团购
        if ($meituan_coupon_data['biz_type'] !== 0) {
            return $this->error('只支持普通团购验券', $meituan_coupon_data);
        }
        //只支持剩余张数大于0的团购券
        if ($meituan_coupon_data['count'] <= 0) {
            return $this->error('团购券可用剩余张数不足', $meituan_coupon_data);
        }

        return $this->success('美团团购券信息', $meituan_coupon_data);
    }
    // 抖音券核销准备
    public function douyinCouponExchange(){
        $user_id = $this->auth->id;
        $category_id = input('category_id', 0);
        $coupon_code = input('coupon_code', '');
        $encrypted_data = input('encrypted_data', '');
        if (strpos($coupon_code, 'http')!==false){
            $coupon_code = '';
        }else{
            $encrypted_data = '';
        }
        //读取门店信息
        $category_info = Category::get($category_id);
        if (!$category_info) {
            return $this->error('门店不存在');
        }
        $row = \app\admin\model\DouyinShop::where('id',$category_info['douyin_shop_id'])->find();
        $auth = \app\admin\model\DouyinAuth::where('id', $row['douyin_auth_id'])->find();
        $result = DouyinLogic::Preparation($auth['app_key'], $auth['app_secret'], $encrypted_data, $coupon_code, $auth['session']);
        if ($result['error_code'] != 0){
            return $this->error($result['description'], $result);
        }
        if (count($result['certificates']) === 0){
            return $this->error('已经兑换完成');
        }
        return $this->success('抖音团购券信息', $result);
    }

    // 抖音券核销
    public function douyinCouponExchangeSystem(){
        $user_id = $this->auth->id;
        $category_id = input('category_id', 0);
        $coupon_code = input('coupon_code', '');
        $encrypted_data = input('encrypted_data', '');
        if (strpos($coupon_code, 'http')!==false){
            $coupon_code = '';
        }else{
            $encrypted_data = '';
        }
        //读取门店信息
        $category_info = Category::get($category_id);
        if (!$category_info) {
            return $this->error('门店不存在');
        }
        $row = \app\admin\model\DouyinShop::where('id',$category_info['douyin_shop_id'])->find();
        $auth = \app\admin\model\DouyinAuth::where('id', $row['douyin_auth_id'])->find();
        $result = DouyinLogic::VerifyCoupon(
            $auth['app_key'],
            $auth['app_secret'],
            $row['open_shop_uuid'],
            $auth['session'],
            $encrypted_data,
            $coupon_code);
        if ($result['res']['error_code'] != 0) {
            $this->error($result['description']);
        }
        $ok=0;
        foreach ($result['goods']['certificates'] as $val) {
            //生成fa_category_quan表数据
            $quan_data = [
                'category_id' => $category_id,
                'user_id' => $user_id,
                'quan_name' => $val['sku']['title'],
                'quan_face_price' => $val['sku']['market_price']/100,
                'quan_balance' => $val['sku']['market_price']/100,
                'quan_price' => $val['amount']['pay_amount']/100,
                //当前时间+90天
                'expire_time' => date('Y-m-d H:i:s', time() + 90 * 24 * 3600),
                'is_used' => 0,
                'order_id' => $result['goods']['order_id'],
                'meituan_quan_code' => $result['goods']['verify_token'],
                'create_time' => date('Y-m-d H:i:s'),
                'used_time' => null,
                'type'=>2,
                'log'=>json_encode($result['res']['verify_results'][$ok], JSON_UNESCAPED_UNICODE)
            ];
            CategoryQuan::create($quan_data);
            CategoryIncome::quan_amount($category_id, $quan_data['quan_price']/100);

            $ok++;
        }
        $this->success("验券成功,已在门店券列表中生成{$ok}张券");
    }


    //美团团购券兑换系统优惠券
    // 正常 http://cfmt.test/api/dylogic/meituanCouponExchangeSystem?coupon_code=2306434509&category_id=38
    // 异常 http://cfmt.test/api/dylogic/meituanCouponExchangeSystem?coupon_code=2306434509&category_id=33


    // 正常 http://cfmt.test/api/dylogic/meituanCouponExchangeSystem?coupon_code=1151945478&category_id=38
    // 异常 http://cfmt.test/api/dylogic/meituanCouponExchangeSystem?coupon_code=1151945478&category_id=33
    /*
     * array(3) {
              ["code"] => int(200)
              ["msg"] => string(12) "验证成功"
              ["data"] => array(1) {
                [0] => array(16) {
                  ["order_id"] => string(24) "167990865121667470856231"
                  ["receipt_code"] => string(10) "2306434509"
                  ["app_shop_id"] => NULL
                  ["open_shop_uuid"] => string(32) "65284a19e73f5962888613daf8a73a89"
                  ["deal_id"] => int(943017524)
                  ["dealgroup_id"] => int(776306224)
                  ["deal_title"] => string(20) "60分钟足部足疗"
                  ["product_type"] => NULL
                  ["product_item_id"] => NULL
                  ["deal_price"] => float(1)
                  ["deal_marketprice"] => float(120)
                  ["mobile"] => string(11) "180****3089"
                  ["biz_type"] => int(0)
                  ["payment_detail"] => array(1) {
                    [0] => array(3) {
                      ["payment_detail_id"] => string(28) "49089458374163761471M9P50101"
                      ["amount"] => float(1)
                      ["amount_type"] => int(10)
                    }
                  }
                  ["receiptEndDate"] => int(1687708799000)
                  ["disclose_mobile_no"] => int(0)
                }
              }
            }
     */
    public function meituanCouponExchangeSystem()
    {
        $user_id = $this->auth->id;
        $category_id = input('category_id', 0);
        $coupon_code = input('coupon_code', '');

        //读取门店信息
        $category_info = Category::get($category_id);
        if (!$category_info) {
            return $this->error('门店不存在');
        }
        //读取门店关联的美团授权信息
        $meituan_auth_info = $category_info->meituan_auth;
        if (!$meituan_auth_info) {
            return $this->error('门店未授权美团');
        }

        $app_key = $meituan_auth_info['app_key'];
        $app_secret = $meituan_auth_info['app_secret'];
        $session = $meituan_auth_info['session'];
        $receipt_code = $coupon_code; //美团团购券码
        $open_shop_uuid = $category_info['meituan_open_id']; //美团门店ID

        //----------------------------
        //读取美团团购券
        $meituan_coupon_info = MeituanLogic::ReceiptPrepare(
            $app_key,
            $app_secret,
            $session,
            $receipt_code,
            $open_shop_uuid
        );
        if ($meituan_coupon_info['code'] !== 200) {
            return $this->error($meituan_coupon_info['msg']);
        }

        $meituan_coupon_data = $meituan_coupon_info['data'];
        //只支持biz_type=0的普通团购
        if ($meituan_coupon_data['biz_type'] !== 0) {
            return $this->error('只支持普通团购验券', $meituan_coupon_data);
        }
        //只支持剩余张数大于0的团购券
        if ($meituan_coupon_data['count'] <= 0) {
            return $this->error('团购券可用剩余张数不足', $meituan_coupon_data);
        }

        //----------------------------
        //随机请求ID,使用时间戳+随机毫秒数
        $requestid = datetime('YmdHis') . "_" . mt_rand(100, 999) . mt_rand(100, 999);

        $count = $meituan_coupon_data['count']; //团购券可用张数
        $app_shop_account = $this->auth->getUser()->username; //账号
        $app_shop_accountname = $this->auth->getUser()->nickname; //昵称
        $meituan_receipt_coupon = MeituanLogic::ReceiptConsume(
            $app_key,
            $app_secret,
            $session,
            $requestid,
            $receipt_code,
            $count,
            $open_shop_uuid,
            $app_shop_account,
            $app_shop_accountname
        );
        //
        file_put_contents(
            'meituan.log',
            "美团验券结果:" . json_encode($meituan_receipt_coupon) . PHP_EOL . PHP_EOL,
            FILE_APPEND
        );


        // $meituan_receipt_coupon=json_decode('{"code":200,"msg":"\u9a8c\u8bc1\u6210\u529f","data":[{"order_id":"167990865121667470856231","receipt_code":"2306434509","app_shop_id":null,"open_shop_uuid":"65284a19e73f5962888613daf8a73a89","deal_id":943017524,"dealgroup_id":776306224,"deal_title":"60\u5206\u949f\u8db3\u90e8\u8db3\u7597","product_type":null,"product_item_id":null,"deal_price":1,"deal_marketprice":120,"mobile":"180****3089","biz_type":0,"payment_detail":[{"payment_detail_id":"49089458374163761471M9P50101","amount":1,"amount_type":10}],"receiptEndDate":1687708799000,"disclose_mobile_no":0}]}',true);

        //如果验券code!=200
        if ($meituan_receipt_coupon['code'] !== 200) {
            return $this->error($meituan_receipt_coupon['msg']);
        }

        $meituan_receipt_coupon_data = $meituan_receipt_coupon['data'];
        // dump($meituan_receipt_coupon);
        // dump($meituan_receipt_coupon_data);
        $ok = 0;
        foreach ($meituan_receipt_coupon_data as $meituan_receipt_coupon_item) {
            //生成fa_category_quan表数据
            $quan_data = [
                'category_id' => $category_id,
                'user_id' => $user_id,
                'quan_name' => $meituan_receipt_coupon_item['deal_title'],
                'quan_face_price' => $meituan_receipt_coupon_item['deal_marketprice'],
                'quan_balance' => $meituan_receipt_coupon_item['deal_marketprice'],
                'quan_price' => $meituan_receipt_coupon_item['deal_price'],
                //当前时间+90天
                'expire_time' => date('Y-m-d H:i:s', time() + 90 * 24 * 3600),
                'is_used' => 0,
                'order_id' => $meituan_receipt_coupon_item['order_id'],
                'meituan_quan_code' => $meituan_receipt_coupon_item['receipt_code'],
                'create_time' => date('Y-m-d H:i:s'),
                'used_time' => null,
            ];
            CategoryQuan::create($quan_data);

            CategoryIncome::quan_amount($category_id, $quan_data['quan_price']);

            $ok++;
        }
        $this->success("验券成功,已在门店券列表中生成{$ok}张券");
    }



    //  http://cfmt.test/api/dylogic/orderAmountPay?order_id=768&quan_id=8
    //根据订单,发起门店余额支付
    public function orderAmountPay()
    {
        $quan_id = input('quan_id', 0);
        $order_id = input('order_id', 0);
        $order_info = Order::get($order_id);
        if (!$order_info) {
            return $this->error('订单不存在');
        }
        if ($order_info['user_id'] != $this->auth->id) {
            return $this->error('订单不存在');
        }
        // //如果调试模式
        // if (config('app_debug') && 1==2) {
        //     $order_info->status = 0;
        //     $order_info->save();
        // }
        if ($order_info['status'] != 0) { //状态:0=未支付,1=待消费,2=消费中,3=已完成,4=已取消,5=续费,6=退款
            return $this->error('订单已支付');
        }

        $fangjian_info = $order_info->fangjian;
        if (!$fangjian_info) {
            return $this->error('订单的房间已经不存在了!');
        }
        $category_info = $fangjian_info->category;
        if (!$category_info) {
            return $this->error('订单的房间对应的门店已经不存在了!');
        }

        $user_id = $this->auth->id;
        //用户门店余额
        $my_category_rmb = UserCategoryRmb::GetAmount($user_id, $category_info->id);
        //用户门店内的优惠券列表
        $my_category_quan_list = CategoryQuan::GetQuanList($user_id, $category_info->id);

        $my_category_quan_info = false;
        if ($quan_id > 0) {
            //使用$quan_id的券获取$my_category_quan_list中的券
            foreach ($my_category_quan_list as $my_category_quan_item) {
                if ($my_category_quan_item['id'] == $quan_id) {
                    $my_category_quan_info = $my_category_quan_item;
                    break;
                }
            }
            if (!$my_category_quan_info) {
                return $this->error('您没有这张券,或此券已被完全使用了!');
            }
        }

        $order_price = $order_info['price'];
        $use_quan_amount = 0;
        if ($my_category_quan_info) {
            $quan_balance = $my_category_quan_info['quan_balance'];
            //需要使用的券金额
            $use_quan_amount = $quan_balance >= $order_price ? $order_price : $quan_balance;
            //如果优惠券余额大于订单金额,则优惠券余额减去订单金额,订单金额为0,优惠券余额为减去订单金额后的余额

            //券被使用后的余额
            $after_quan_balance = $quan_balance - $use_quan_amount;
            //订单使用券后的金额
            $order_price = $order_price - $use_quan_amount;
        }

        //如果用户门店余额小于了订单金额
        if ($my_category_rmb < $order_price) {
            return $this->error("您的门店余额不足{$order_price}元,请充值后再支付!");
        }
        //$order_price不能小于0
        if ($order_price < 0) {
            return $this->error("实际支付订单金额不能小于0!");
        }

        // $user_info = $this->auth->getUser();

        //开启事务
        Db::startTrans();
        try {
            //会员门店余额变更表 user_category_rmb_log
            UserCategoryRmb::change(
                $user_id,
                $category_info->id,
                -1 * $order_price,
                "门店余额支付订单{$order_id}," . ($my_category_quan_info ? "使用优惠券{$my_category_quan_info['quan_name']},券余额{$my_category_quan_info['quan_balance']}" : "")
            );

            //如果使用了优惠券,优惠券余额变更
            if ($my_category_quan_info) {
                CategoryQuan::change(
                    $quan_id,
                    $user_id,
                    $category_info->id,
                    -1 * $use_quan_amount,
                    "门店余额支付订单{$order_id},使用优惠券{$my_category_quan_info['quan_name']}"
                );
            }

            Order::updateOrderStatusToPayed($order_id, 1, $quan_id, $use_quan_amount, $order_price, 2);


            //订单续费
            Order::xufeiOrder($order_id);

            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error('订单支付失败', $e);
        }

        return $this->success('订单支付成功');
    }

    //  http://cfmt.test/api/dylogic/orderWxPay?order_id=768
    //根据订单,发起微信支付
    public function orderWxPay()
    {
        $quan_id = input('quan_id', 0);
        $order_id = input('order_id', 0);
        $order_info = Order::get($order_id);
        if (!$order_info) {
            return $this->error('订单不存在');
        }
        if ($order_info['user_id'] != $this->auth->id) {
            return $this->error('订单不存在');
        }
        // //如果调试模式
        // if (config('app_debug') && 1==2) {
        //     $order_info->status = 0;
        //     $order_info->save();
        // }

        if ($order_info['status'] != 0) {
            return $this->error('订单已支付');
        }

        //需要使用微信支付的订单,必须要有openid
        if (!$this->auth->getUser()->openid) {
            return $this->error('您还没有绑定微信,请先绑定微信!');
        }

        $fangjian_info = $order_info->fangjian;
        if (!$fangjian_info) {
            return $this->error('订单的房间已经不存在了!');
        }
        $category_info = $fangjian_info->category;
        if (!$category_info) {
            return $this->error('订单的房间对应的门店已经不存在了!');
        }

        $user_id = $this->auth->id;

        //用户门店内的优惠券列表
        $my_category_quan_list = CategoryQuan::GetQuanList($user_id, $category_info->id);

        $my_category_quan_info = false;
        if ($quan_id > 0) {
            //使用$quan_id的券获取$my_category_quan_list中的券
            foreach ($my_category_quan_list as $my_category_quan_item) {
                if ($my_category_quan_item['id'] == $quan_id) {
                    $my_category_quan_info = $my_category_quan_item;
                    break;
                }
            }
            if (!$my_category_quan_info) {
                return $this->error('您没有这张券,或此券已被完全使用了!');
            }
        }

        $order_price = $order_info['price'];
        $use_quan_amount = 0;
        if ($my_category_quan_info) {
            $quan_balance = $my_category_quan_info['quan_balance'];
            //需要使用的券金额
            $use_quan_amount = $quan_balance >= $order_price ? $order_price : $quan_balance;
            //如果优惠券余额大于订单金额,则优惠券余额减去订单金额,订单金额为0,优惠券余额为减去订单金额后的余额

            //券被使用后的余额
            $after_quan_balance = $quan_balance - $use_quan_amount;
            //订单使用券后的金额
            $order_price = $order_price - $use_quan_amount;

        }

        //$order_price不能小于0
        if ($order_price < 0) {
            return $this->error("实际支付订单金额不能小于0!");
        }


        Order::updateOrderStatusToPayed($order_id, 0, $quan_id, $use_quan_amount, $order_price, 0);

        if ($order_price == 0) {
            Order::updateOrderStatusToPayed($order_id, 1, $quan_id, $use_quan_amount, $order_price, 2);
            //如果使用了优惠券,优惠券余额变更
            if ($my_category_quan_info) {
                CategoryQuan::change(
                    $quan_id,
                    $user_id,
                    $category_info->id,
                    -1 * $use_quan_amount,
                    "门店余额支付订单{$order_id},使用优惠券{$my_category_quan_info['quan_name']}"
                );
            }
            //订单续费
            Order::xufeiOrder($order_id);
            $this->error('需要微信支付的金额为0元,现在已直接支付订单!',[],200);
        }else if($my_category_quan_info){
            //锁定优惠券
            CategoryQuan::lockQuan($quan_id);
        }


        $return_url = url('/', '', true, true);
        $notify_url = url('api/dylogic/pay_order_notifyx', ['uniacid' => config('site.uniacid')], true, true);
        // // 调试模式下,将域名替换为 chashi.ymq.xiaoenguanyijia.site
        // if (config('app_debug') && 1==2) {
        //     $return_url = str_replace('cfmt.test', 'chashi.ymq.xiaoenguanyijia.site', $return_url);
        //     $notify_url = str_replace('cfmt.test', 'chashi.ymq.xiaoenguanyijia.site', $notify_url);
        // }

        $user_openid = $this->auth->getUser()->openid;

        $order_title = $order_info['title'];
        // //如果当前是调试模式
        // if (config('app_debug') && 1==2) {
        //     $order_title = "测试付:{$order_price}";
        //     //调试时,可以把$order_price设置为0.01,方便测试
        //     $order_price = 0.01;
        // }

        $params = [
            'amount' => $order_price,
            // 'orderid'=>$order_id."_".rand(10000,99999),
            'orderid' => $order_id . "_" . time(),
            'type' => "wechat",
            'title' => $order_title,
            'notifyurl' => $notify_url,
            'returnurl' => $return_url,
            'method' => "miniapp",
            'openid' => $user_openid,
            'auth_code' => "验证码",
            //time_expire订单过期时间,格式:20091225091010
            // 'time_expire'=> date('YmdHis', time() + 30),
            // 'time_expire'=> date('YmdHis', time() + 30 * 60),
        ];

        Log::write("发起微信支付:{$order_id},{$order_price},{$user_openid},{$order_title},{$notify_url},{$return_url}");

        $result = \addons\epay\library\Service::submitOrder($params);
        //因为不成功已经在上面进行了拦截了.
        $this->success('发起支付成功', $result->all());
    }


    // http://cfmt.test/api/dylogic/pay_order_notifyx?paytype=wechat
    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/pay_order_notifyx?paytype=wechat
    // https://wqbanchangdikaifa.kaifa.yimaoqi.cn/addons/ymq_changdi/public/index.php/api/dylogic/pay_order_notifyx?paytype=wechat
    public function pay_order_notifyx()
    {
        //获取当前请求的完整URL
        $url = $this->request->url(true);
        Log::write("支付回调,URL:{$url}");
        //记录完整的回调数据
        Log::write("支付回调,数据:" . json_encode($this->request->request()));

        // if ($payNotifyData['return_code'] === 'FAIL' && $payNotifyData['result_code'] === 'FAIL') {
        //     // 用户取消支付，执行解锁优惠券的操作
        //     // 解锁优惠券的代码
        // }


        $paytype = 'wechat';
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            Log::write("支付回调,签名错误:{$paytype}");
            return;
        }
        $data = $pay->verify();
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            //根据订单号,获取订单信息
            $order_info = Order::get($out_trade_no);
            if (!$order_info) {
                Log::write("支付回调,订单不存在:{$out_trade_no}");
                return $this->error('订单不存在');
            }

            //如果订单已经支付过了,则不再进行处理
            if ($order_info['status'] != 0) {
                Log::write("支付回调,订单已支付:{$out_trade_no}");
                return $this->error('订单已支付');
            }

            $fangjian_info = $order_info->fangjian;
            if (!$fangjian_info) {
                Log::write("支付回调,订单的房间已经不存在了:{$out_trade_no}");
                return $this->error('订单的房间已经不存在了!');
            }
            $category_info = $fangjian_info->category;
            if (!$category_info) {
                Log::write("支付回调,订单的房间对应的门店已经不存在了:{$out_trade_no}");
                return $this->error('订单的房间对应的门店已经不存在了!');
            }

            //调试模式
            // if (config('app_debug') == false) {
            //如果不是调试模式,则需要验证订单金额是否正确
            if ($order_info['real_price'] != $payamount) {
                Log::write("支付回调,非调试模式验证金额,订单金额不正确:{$out_trade_no}");
                return $this->error('订单金额不正确');
            }
            // }

            //是否使用了优惠券
            $order_id = $order_info['id'];
            $quan_id = $order_info['quan_id'];
            $use_quan_amount = $order_info['quan_price'];
            $user_id = $order_info['user_id'];
            if ($quan_id > 0 && CategoryQuan::isLock($quan_id)) {
                //解锁优惠券
                CategoryQuan::unlockQuan($quan_id);
                //如果使用了优惠券,则需要把优惠券的金额扣掉
                CategoryQuan::change(
                    $quan_id,
                    $user_id,
                    $category_info->id,
                    -1 * $use_quan_amount,
                    "门店余额支付订单{$order_id},微信支付时,使用此优惠券."
                );
            }
            Log::write("支付回调,订单支付成功:{$out_trade_no},{$payamount},{$quan_id},{$use_quan_amount}");

            //订单状态改为已支付
            Order::updateOrderStatusToPayed($order_id, 1, $quan_id, $use_quan_amount, $payamount, 1);


            //订单续费
            Order::xufeiOrder($order_id);
            Order::where('id', $order_id)->update([
                'transaction_id' => $data['transaction_id']
            ]);
            CategoryIncome::order_pay_amount($category_info->id, $payamount);
        } catch (Exception $e) {
            Log::write("支付回调,发生异常:{$e->getMessage()}");
            return $this->error('发生异常');
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    // http://cfmt.test/api/dylogic/wxPayRecharge?category_id=34&price=100
    //给某个门店充值余额
    public function wxPayRecharge()
    {
        $category_id = input('category_id', 0);
        $price = input('price', 0);
        $id = input('id', 0);
        $category_info = Category::get($category_id);
        if (!$category_info) {
            return $this->error('门店不存在!');
        }
        //充值金额必须大于0
        if ($price <= 0) {
            return $this->error('充值金额必须大于0!');
        }

        $user_info = $this->auth->getUser();
        $user_id = $this->auth->id;
        //openid如果不存在
        if (!$user_info['openid']) {
            $user_info['openid'] = User::getOpenid($user_id);
        }
        $user_openid = $user_info['openid'];

        //使用微信支付
        $paytype = 'wechat';
        $order_id = $category_id . "_" . time();
        $order_price = $price;
        $return_url = url('/', '', true, true);
        $notify_url = url('api/dylogic/pay_recharge_notifyx', ['uniacid' => config('site.uniacid')], true, true);
        // 调试模式下,将域名替换为 chashi.ymq.xiaoenguanyijia.site
        // if (config('app_debug') && 1==2) {
        //     $return_url = str_replace('cfmt.test', 'chashi.ymq.xiaoenguanyijia.site', $return_url);
        //     $notify_url = str_replace('cfmt.test', 'chashi.ymq.xiaoenguanyijia.site', $notify_url);
        // }
        $order_title = "门店充值:" . $category_info['name'];

        $pay_order_no = $order_id . "_" . time();


        //记录充值记录 RechargeRecord
        $recharge_record_data = [
            'user_id' => $user_id,
            'category_id' => $category_id,
            'type' => 'wechat',
            'order_no' => $pay_order_no,
            'trade_no' => '',
            'amount' => $order_price,
            'is_success' => 0,
            'create_time' => date('Y-m-d H:i:s'),
            'credit_time' => null,
            'text_log' => '',
            'record_time' => date('Y-m-d H:i:s'),
            'rule_id' => $id
        ];

        // //调试期间金额设置为1分钱
        // if (config('app_debug') == true) {
        //     $order_price = 0.01;
        // }

        $params = [
            'amount' => $order_price,
            // 'orderid'=>$order_id."_".rand(10000,99999),
            'orderid' => $pay_order_no,
            'type' => "wechat",
            'title' => $order_title,
            'notifyurl' => $notify_url,
            'returnurl' => $return_url,
            'method' => "miniapp",
            'openid' => $user_openid,
            'auth_code' => "验证码"
        ];

        Log::write("发起微信支付:{$pay_order_no},{$order_price},{$user_openid},{$order_title},{$notify_url},{$return_url}");

        $result = \addons\epay\library\Service::submitOrder($params);

        RechargeRecord::create($recharge_record_data);

        //因为不成功已经在上面进行了拦截了.
        $this->success('发起微信充值', $result->all());
    }



    // http://cfmt.test/api/dylogic/pay_recharge_notifyx?paytype=wechat
    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/pay_recharge_notifyx?paytype=wechat

    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/pay_recharge_notifyx.html
    //门店充值回调 pay_recharge_notifyx
    public function pay_recharge_notifyx()
    {
        //获取当前请求的完整URL
        $url = $this->request->url(true);
        Log::write("充值支付回调,URL:{$url}");
        //记录完整的回调数据
        Log::write("充值支付回调,数据:" . json_encode($this->request->request()));


        $paytype = 'wechat';
        $pay = \addons\epay\library\Service::checkNotify($paytype);
        if (!$pay) {
            echo '签名错误';
            Log::write("充值支付回调,签名错误:{$paytype}");
            return;
        }
        $data = $pay->verify();
        Log::write("充值支付回调,验证后的数据:" . json_encode($data));
        //{"appid":"wxd9ae69f183ed1214","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1631042255","nonce_str":"zOawqA7TdTgNoQNd","openid":"oMLPn4mHHM34k7-6zTZzVPQwpmAw","out_trade_no":"33_1679981618_1679981618","result_code":"SUCCESS","return_code":"SUCCESS","sign":"800CBB0556C2DC1F74801B0A8162466B","time_end":"20230328133401","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001745202303281484685400"}
//        $paytype = 'wechat';
//        $data['total_fee'] = 20000;
//        $data['out_trade_no'] = '40_1692262171_1692262171';
//        $data['transaction_id'] = 111;
        // $data=json_decode('{"appid":"wxd9ae69f183ed1214","bank_type":"OTHERS","cash_fee":"1","fee_type":"CNY","is_subscribe":"N","mch_id":"1631042255","nonce_str":"LYDvXZtCw1NNTwLk","openid":"oMLPn4mHHM34k7-6zTZzVPQwpmAw","out_trade_no":"35_1679984435_1679984435","result_code":"SUCCESS","return_code":"SUCCESS","sign":"8C94F21E507DCF19677F5B3C119D2296","time_end":"20230328142048","total_fee":"1","trade_type":"JSAPI","transaction_id":"4200001721202303288717054481"}',true);
        try {
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];


            //记录充值记录 RechargeRecord
            //在RechargeRecord找到 order_no=$out_trade_no 的记录,并且is_success=0的记录
            $recharge_record = RechargeRecord::where('order_no', $out_trade_no)->find();
            if (!$recharge_record) {
                Log::write("充值支付回调,找不到充值记录:{$out_trade_no}");
                return $this->error('找不到充值记录');
            }
            if ($recharge_record['is_success'] == 1) {
                Log::write("充值支付回调,充值记录在此之前就已经成功:{$out_trade_no}");
                return $this->error('充值记录在此之前就已经成功');
            }

            //调试模式
            // if (config('app_debug') == false) {
            //如果不是调试模式,则需要验证订单金额是否正确
            if ($recharge_record['amount'] != $payamount) {
                Log::write("充值支付回调,非调试模式验证金额,订单金额不正确:{$out_trade_no}");
                return $this->error('充值支付订单回调金额不正确');
            }
            // }


            $recharge_record->is_success = 1;
            $recharge_record->trade_no = $data['transaction_id'];
            $recharge_record->credit_time = date('Y-m-d H:i:s');
            $recharge_record->text_log = "微信回调成功";
            $recharge_record->save();

            $user_id = $recharge_record->user_id; //充值用户
            $category_id = $recharge_record->category_id; //充值门店
            $order_price = $recharge_record->amount; //充值金额

            //根据充值金额获取充值赠送金额
            $give_amount = RechargeRule::GetPriceRechargeGiveAmount($order_price, $category_id);
            $total_amount = $order_price + $give_amount; //充值总金额

            //给用户的此门店加余额
            UserCategoryRmb::change(
                $user_id,
                $category_id,
                $total_amount,
                "门店余额充值,充值金额:{$order_price},赠送金额:{$give_amount},总入账金额:{$total_amount}"
            );

            UserCategoryRmb::upLevel(
                $user_id,
                $category_id,
                $recharge_record['rule_id']
            );

            CategoryIncome::wechat_recharge_amount($category_id, $order_price);
            // 结算服务费
            $order_commission_type = sConfig::get('site.order_commission_type'); //
            $order_commission = floatval(sConfig::get('site.order_commission'));
            $order_commission = $order_commission ? $order_commission : 0;
            $order_commission_type_text = '';
            if ($order_commission_type == 1) {
                $order_commission_type_text = "服务费固定金额：{$order_commission}";
            } elseif ($order_commission_type == 0) {
                $order_commission_type_text = "服务费百分比：{$order_commission}%";
            }
            $settlement_money = $order_price;
            $send_settlement_money = $settlement_money;
            if ($order_commission_type == 1) {
                $send_settlement_money = $settlement_money - $order_commission;
            } elseif ($order_commission_type == 0) {
                $send_settlement_money = round($settlement_money - ($settlement_money * $order_commission / 100), 2);
            }
            $rs1 = \app\admin\model\CategoryMoneyLog::_do($category_id, $send_settlement_money, 2, "用户门店余额充值，订单编号:{$out_trade_no}，充值金额:{$order_price}，$order_commission_type_text");


        } catch (Exception $e) {
            Log::write("充值支付回调,发生异常:{$e->getMessage()}");
            return $this->error('发生异常');
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        return $pay->success()->send();
    }

    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/get_order_detail?order_id=768
    //获取订单详情
    public function get_order_detail()
    {
        $order_id = $this->request->request('order_id');
        $order = Order::where('id', $order_id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        $order->user;
        $order->fangjian;
        $order->fangjian->image = cdnurl($order->fangjian->image, true);
        $order->fangjian->category;
        return $this->success('获取成功', $order);
    }


    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/get_mini_images
    // http://cfmt.test/api/dylogic/get_mini_images
    // 获取主图
    public function get_mini_images()
    {
        $image_list = MiniImage::where('show_switch', 1)->select();
        foreach ($image_list as $key => $value) {
            $value->main_image = cdnurl($value->main_image, true);
        }
        return $this->success('获取成功', $image_list);
    }

    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/get_config
    // http://cfmt.test/api/dylogic/get_config
    //获取config中的配置项
    public function get_config()
    {
        $names = [
            'name',
            'join_tel',
            'icon_img',
            'balance_status',
        ];
        $config_list = Config::where('name', 'in', $names)->column('value', 'name');
        $config_list['icon_img'] = cdnurl($config_list['icon_img'], true);
        return $this->success('获取成功', $config_list);
    }

    // http://cfmt.test/api/dylogic/test
    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/test
    public function test()
    {
        // CategoryIncome::quan_amount(1, 55);
        // CategoryIncome::wechat_recharge_amount(1, 55);
        // CategoryIncome::order_pay_amount(1, 55);
        // Order::xufeiOrder(836);
    }



    // http://chashi.ymq.xiaoenguanyijia.site/api/dylogic/cancel_order?order_id=768
    // http://cfmt.test/api/dylogic/cancel_order?order_id=768
    //取消订单
    public function cancel_order()
    {
        //status 0未支付 1待消费 2消费中 3已完成 4已取消 5已退款
        $order_id = $this->request->request('order_id');
        $order = Order::where('id', $order_id)->find();
        if (!$order) {
            return $this->error('订单不存在');
        }
        if ($order['status'] == 2) {
            return $this->error('消费中不允许退款');
        }
        if ($order['status'] == 3) {
            return $this->error('已完成不允许退款');
        }
        if ($order['status'] == 4) {
            return $this->error('已取消不允许退款');
        }
        if ($order['status'] == 5) {
            return $this->error('已退款不允许退款');
        }

        //通过订单模型获取房间模型
        $fangjian = $order->fangjian;
        if (!$fangjian) {
            return $this->error('房间已不存在,不能退款');
        }
        //通过房间模型获取门店模型
        $category = $fangjian->category;
        if (!$category) {
            return $this->error('门店已不存在,不能退款');
        }

        //读取门店允许退款的时间分钟
        $cancel_order_min = $category->cancel_order_min;

        //
        // dump($category->toArray());
        // dump($cancel_order_min);
        // dump($order['status']);
        // dump($order['quan_id']);

        if ($order->x_status == 2) {
            $order->status = 4;
            $order->save();
            return $this->success('取消成功');
        }

        if ($order['status'] == 0) {
            //直接修改订单状态,并解锁房间,并解锁优惠券

            //解锁房间,因为订单状态改变后,订单时间作废了,房间也就自动解锁了.

            $quan_id = $order['quan_id'];
            if ($quan_id) {
                //解锁优惠券
                CategoryQuan::where('id', $quan_id)->update(['is_lock' => 0, 'lock_time' => null]);
            }
            $order->status = 4;
            $order->save();
            return $this->success('取消成功');
        }

        if ($order['status'] == 1) {
            //服务预定开始时间, $order['fuwu']
            $fuwu_start_time = strtotime($order['fuwu']);
            //判断是否超过了允许取消的时间
            if (time() - $cancel_order_min * 60 > $fuwu_start_time) {
                return $this->error("距离消费时间不足{$cancel_order_min}分钟,不允许取消");
            }
            //如果使用了优惠券,订单优惠券金额加回到优惠券中
            $quan_id = $order['quan_id'];
            $user_id = $order['user_id'];
            $use_quan_amount = $order['quan_price'];
            if ($quan_id && $use_quan_amount > 0) {
                CategoryQuan::change(
                    $quan_id,
                    $user_id,
                    $category->id,
                    $use_quan_amount,
                    "订单退款,订单ID:{$order_id},优惠券ID:{$quan_id}加回余额{$use_quan_amount}元"
                );
            }
            //实际支付金额
            $use_real_price = $order['real_price'];
            if ($use_real_price > 0) {
                //将实际支付金额加回到用户门店余额中
                UserCategoryRmb::change(
                    $user_id,
                    $category->id,
                    $use_real_price,
                    "订单退款,订单ID:{$order_id},加回余额{$use_real_price}元"
                );
            }
            //直接修改订单状态,并解锁房间,并解锁优惠券
            $order->status = 4;
            $order->save();
            return $this->success("取消成功,已退款至门店余额:{$use_real_price}元,已退优惠券金额:{$use_quan_amount}元");
        }

        return $this->success('取消失败,订单状态异常!');
    }

    public function profitSharingNotify()
    {
        $data = $this->request->param();
        file_put_contents('log.txt', json_encode($data, 256), FILE_APPEND);
    }
}
